package com.juzi.wopu.web;

import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import com.juzi.wopu.domain.Employee;
import com.juzi.wopu.domain.Role;
import com.juzi.wopu.query.EmployeeQuery;
import com.juzi.wopu.query.PageList;
import com.juzi.wopu.service.IEmployeeService;
import com.juzi.wopu.service.IRoleService;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

public class EmployeeAction extends CRUDAaction<Employee> {
	
	private static final long serialVersionUID = 1L;

	private IEmployeeService employeeService;
	
	private IRoleService roleService;

	private Employee employee = new Employee();
	
	private EmployeeQuery baseQuery = new EmployeeQuery();
	
	private PageList pageList;
	
	private Long[] dis;

	public void setEmployeeService(IEmployeeService employeeService) {
		this.employeeService = employeeService;
	}

//	public void setDepartmentService(IDepartmentService departmentService) {
//		this.departmentService = departmentService;
//	}
	
	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}
	
	private String username;
	
	public String check() throws Exception {
		HttpServletResponse response=ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		if(id==null){
			out.print("{\"valid\":"+employeeService.findByUsername(username)+"}");
		}else{
			Employee oldemployee = employeeService.get(id);
			String oldUsername = oldemployee.getUsername();
			if(oldUsername.equals(username)){
				out.print("{\"valid\":true}");
			}else{
				out.print("{\"valid\":"+employeeService.findByUsername(username)+"}");
			}
		}		
		return NONE;
	}

	@Override
	protected void list() {
		this.pageList = employeeService.findByQuery(baseQuery);
		/*putContext("allDepts", departmentService.getAll());*/
		putContext("allRoles", roleService.getAll());
	}

	@Override
	public String input() throws Exception {
		if (id != null) {
			employee = employeeService.get(id);
		}

		/*putContext("allDepts", departmentService.getAll());*/
		putContext("allRoles", roleService.getAll());
		return INPUT;

	}

	public void validateSave() {
		if (StringUtils.isBlank(employee.getUsername())) {
			addFieldError("username", "用户名不能为空");
		}
	}

	@Override
    @InputConfig(methodName="input")
	public String save() throws Exception {
		/*Department department = employee.getDepartment();
		if (department != null && department.getId() == -1L) {
			employee.setDepartment(null);
		}*/
		
		if(dis != null){
			for (long id : dis) {
				employee.getRoles().add(new Role(id));
			}
		}
		
		if(id==null){
			baseQuery.setCurrentPage(Integer.MAX_VALUE);
		}
		employeeService.save(employee);
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		try {

			if (id != null) {
				employeeService.delete(id);
				out.print("{\"success\":true,\"msg\":\"删除成功\"}");
			}else{
				out.print("{\"success\":false,\"msg\":\"没有删除成功\"}");
			}
		} catch (Exception e) {
			out.print("{\"success\":false,\"msg\":\"异常信息:"+e.getMessage()+"\"}");
		}
		return null;
	}

	@Override
	public void prepareInput() throws Exception {
		if (id != null) {
			employee = employeeService.get(id);
			Set<Role> roles = employee.getRoles();
			dis=new Long[roles.size()];
			int index=0;
			for (Role role : roles) {
				dis[index]=role.getiId();
				index++;
			}
		}
	}

	@Override
	public void prepareSave() throws Exception {
		if (id == null) {
			employee = new Employee();
		} else {
			employee = employeeService.get(id);
			employee.getRoles().clear();
			/*employee.setDepartment(null);*/
		}
	}
	
	private InputStream inputStream;
	public InputStream getInputStream() {
		return inputStream;
	}
	
	public String getFileName() throws UnsupportedEncodingException {
		return new String("员工列表.xlsx".getBytes("GBK"), "ISO8859-1");
	}
	
	public String download() throws Exception {
		List<String[]> data=new ArrayList<>();
		baseQuery.setPageSize(Integer.MAX_VALUE);
		PageList pageList=employeeService.findByQuery(baseQuery);
		System.out.println("数据总数："+pageList.getTotalcount());
		
		String[] heads={"用户名","密码","邮箱地址","年龄","部门名称"};
		List<Employee> dataList=pageList.getRows();
		System.out.println(dataList);
		
		for(int i=0;i<dataList.size();i++){
			Employee emp=dataList.get(i);
			String[] strings=new String[heads.length];
			strings[0]=emp.getUsername()==null?"":emp.getUsername();
			strings[1]=emp.getPassword()==null?"":emp.getPassword();
			strings[2]=emp.getEmail()==null?"":emp.getEmail();
			strings[3]=emp.getAge()==null?"":emp.getAge()+"";
			/*strings[4]=emp.getDepartment()==null?"":emp.getDepartment().getName();*/
			data.add(strings);
		}
		this.inputStream=employeeService.imp(heads, data);
		return "download";
	}
	
	@Override
	public Employee getModel() {
		return employee;
	}

	public PageList getPageList() {
		return pageList;
	}

	public EmployeeQuery getBaseQuery() {
		return baseQuery;
	}

	public void setBaseQuery(EmployeeQuery baseQuery) {
		this.baseQuery = baseQuery;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public Long[] getDis() {
		return dis;
	}

	public void setDis(Long[] dis) {
		this.dis = dis;
	}
}
